//
//  RZConversationViewController.m
//  RZIM
//
//  Created by reyzhang on 2021/8/4.
//

#import "RZConversationViewController.h"
#import "RZConversationViewLayout.h"
#import "RZSystemSoundPlayer.h"
#import "RZKitUtility.h"
#import "RZConversationDataSource.h"
#import "RZIMClient.h"
#import "RZMessageBaseCell.h"
#import "RZMessageCellTool.h"
#import "NetworkTools.h"
//#import "VoiceConverter.h"
#import "RZApiManager.h"
#import "NSDictionary+Helper.h"
#import "RZVoiceMessageCell.h"
#import "RZImageSlideViewController.h"
#import "NSDictionary+Helper.h"
#import "RZConversationCollectionViewHeader.h"
#import "RZVoicePlayer.h"
#import "RZVideoPreviewViewController.h"
#import "RZSocketRocketManager.h"
#import "UIManager.h"



#define COLLECTION_VIEW_REFRESH_CONTROL_HEIGHT 30

@interface RZConversationViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,RZChatSessionInputBarControlDelegate,UIScrollViewDelegate,RZMessageCellDelegate>

#pragma mark 通用
@property (nonatomic, copy) NSString *navigationTitle;

@property (nonatomic, strong) RZConversationDataSource *dataSource;


@property (nonatomic, strong) UITapGestureRecognizer *resetBottomTapGesture;

@property (nonatomic, strong) NSString *toUserId; //对方的id

@end

@implementation RZConversationViewController


#pragma mark - 初始化
- (id)initWithConversationType:(RZConversationType)conversationType targetId:(NSString *)targetId label:(NSInteger)label {
    self = [super init];
    if (self) {
        self.conversationType = conversationType;
        self.targetId = targetId;
        self.label = label;
    }
    return self;
}


- (id)initWithConversationType:(RZConversationType)conversationType targetId:(NSString *)targetId {
    return [self initWithConversationType:conversationType targetId:targetId label:0];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    self.isConversationAppear = NO;
    self.conversationDataRepository = [[NSMutableArray alloc] init];
    self.conversationMessageCollectionView = nil;

    self.displayUserNameInCell = YES;
    self.isContinuousPlaying = NO;
    self.dataSource = [[RZConversationDataSource alloc] init:self];
    self.defaultRemoteHistoryMessageCount = 10;
//    self.needAutoScrollToBottom = YES;
    [self registerNotification];
}


#pragma mark - Life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self registerNotification];
    
    self.view.backgroundColor = [UIColor colorWithRed:245/255.0 green:246/255.0 blue:249/255.0 alpha:1];
    [self.view addSubview:self.conversationMessageCollectionView]; //添加collectionV
    [self.view sendSubviewToBack:self.conversationMessageCollectionView];
   
    [self registerSectionHeaderView];
    if (self.conversationType == ConversationType_PRIVATE) { //如果是私聊会话，需要先加入
        self.toUserId = self.targetId;
        [[RZIMClient sharedClient] joinPrivateChatWithTargetId:self.targetId label:self.label success:^(RZGroupInfo * _Nonnull groupInfo) {
            self.targetId = groupInfo.gid; //目标id,转成群组 id
            [[RZSystemSoundPlayer defaultPlayer] setIgnoreSoundByConversationId:self.targetId];
            [self loadMessageList];
        } error:^(RZErrorCode nErrorCode, NSString * _Nullable errorMessage) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
        
    }else {
        [self loadMessageList];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //响铃设置 - 忽略此消息的响铃
    [[RZSystemSoundPlayer defaultPlayer] setIgnoreSoundByConversationId:self.targetId];
    
    //禁止所有滑动返回的手势, 让button的touch事件能够正常响应
    self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan = NO;

    //添加重置底部工具条手势
    [self.conversationMessageCollectionView addGestureRecognizer:self.resetBottomTapGesture];

    [self.chatSessionInputBarControl containerViewWillAppear];
    
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    self.isConversationAppear = YES;
    [self.chatSessionInputBarControl containerViewDidAppear];
    self.navigationTitle = self.navigationItem.title;
    
    RZMessageInfo *latestMessage = self.conversationDataRepository.lastObject;
    [self clearUnReadMessage:latestMessage];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.conversationMessageCollectionView removeGestureRecognizer:self.resetBottomTapGesture];
    [[RZSystemSoundPlayer defaultPlayer] resetIgnoreConversation];
    [self stopPlayingVoiceMessage];
    self.isConversationAppear = NO;
    
    self.navigationItem.title = self.navigationTitle;
    [self.chatSessionInputBarControl containerViewWillDisappear];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"聊天会话释放%s======%@", __func__, self);
}


- (float)getSafeAreaExtraBottomHeight {
    return [RZKitUtility getWindowSafeAreaInsets].bottom;
}

- (void)loadMessageList {
    //根据targetId 读取会话信息。 再根据会话信息，获取会话下的消息列表
    [[RZIMClient sharedClient] getConversationWithTargetId:self.targetId success:^(RZConversation * _Nonnull conversation) {
        self.conversation = conversation;
        if ([self.title isEqualToString:@""]) {
            self.title = self.conversation.conversationType == ConversationType_PRIVATE ?
            self.conversation.targetName :
            [NSString stringWithFormat:@"%@(%ld)",self.conversation.targetName,(long)self.conversation.userList.count];
        }
        [self.dataSource getInitialMessage:conversation];
    } error:^(RZErrorCode nErrorCode, NSString * _Nullable errorMessage) {
        [self.navigationController popViewControllerAnimated:YES];
    }];

}



- (void)clearUnReadMessage:(RZMessageInfo *)message {
    if (message && [message isKindOfClass:[RZMessageInfo class]]) {
        
        RZMessage *socketMsg = [RZMessage new];
        socketMsg.gid = message.gid;
        //构造具体的消息
        RZMessageContent *content = [RZMessageContent new];
        content.msgId = message.mid;
        content.msgType = 0;
        socketMsg.message = content;
        
        [[RZSocketRocketManager shareInstance] sendMesage:socketMsg];
        
    }
}
#pragma mark - Helper
- (void)registerSectionHeaderView {
    [self.conversationMessageCollectionView registerClass:[RZConversationCollectionViewHeader class]
                               forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                      withReuseIdentifier:@"RefreshHeadView"];
}

- (void)tap4ResetDefaultBottomBarStatus:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        if (self.chatSessionInputBarControl.currentBottomBarStatus != KBottomBarDefaultStatus &&
            self.chatSessionInputBarControl.currentBottomBarStatus != KBottomBarRecordStatus) {
            [self.chatSessionInputBarControl resetToDefaultStatus];
        }
    }
}


- (void)stopPlayingVoiceMessage {
    if ([RZVoicePlayer defaultPlayer].isPlaying) {
        [[RZVoicePlayer defaultPlayer] stopPlayVoice];
    }
}
#pragma mark - Notification selector

- (void)registerNotification {

    //注册接收消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveMessageNotification:)
                                                 name:RZNotification_SocketRocketDidReceive
                                               object:nil];
    

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleAppResumeNotification)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleWillResignActiveNotification)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];


    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(stopPlayingVoiceMessage)
                                                 name:UIWindowDidResignKeyNotification
                                               object:nil];

    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(currentViewFrameChange:)
                                                 name:UIApplicationWillChangeStatusBarFrameNotification
                                               object:nil];
}


/**
 收到socket消息后的处理
 */
- (void)didReceiveMessageNotification:(NSNotification *)notification {
    RZMessage *rzMessage = notification.object;
    self.needAutoScrollToBottom = YES;
    [self.dataSource didReceiveMessageNotification:rzMessage];
}


- (void)handleAppResumeNotification {
    self.isConversationAppear = YES;
    [self.conversationMessageCollectionView reloadData];
    if ([[RZIMClient sharedClient] connectStatus] == ConnectionStatus_Connected) {
//        [self.util syncReadStatus];
//        [self.util sendReadReceipt];
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        [[RZIMClient sharedClient] clearMessagesUnreadStatus:self.conversationType targetId:self.targetId];
    });
}

- (void)handleWillResignActiveNotification {
    self.isConversationAppear = NO;
    [self.chatSessionInputBarControl endVoiceRecord];
    //直接从会话页面杀死 app，保存或者清除草稿
//    [self.util saveDraftIfNeed];
}


- (void)currentViewFrameChange:(NSNotification *)notification {
    if(!self.isConversationAppear) {
        return;
    }
    [self.chatSessionInputBarControl containerViewSizeChanged];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.conversationDataRepository.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    RZMessageInfo *model = [self.conversationDataRepository objectAtIndex:indexPath.row];
    
    RZMessageBaseCell *cell = [RZMessageBaseCell createInstanceWithCollectionView:collectionView forMessage:model atIndexPath:indexPath];
    [cell setDataModel:model];
    cell.delegate = self;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        RZConversationCollectionViewHeader *headerView =
            [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                               withReuseIdentifier:@"RefreshHeadView"
                                                      forIndexPath:indexPath];
        self.collectionViewHeader = headerView;
        return headerView;
    }
    return nil;
}

//修复ios7下不断下拉加载历史消息偶尔崩溃的bug
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    RZMessageInfo *model = [self.conversationDataRepository objectAtIndex:indexPath.row];
    [self.dataSource setModelIsDisplayNickName:model]; //设置是否显示昵称
    model.conversationType = self.conversationType; //指定会话类型
    
    
    //如果已经获取过cellSize,直接返回
    if(model.cellSize.width != 0 && model.cellSize.height !=0) {
        return model.cellSize;
    }
    
    //如果未获取，通过调用类方法获
    NSString *key = [RZMessageCellTool getMessageCellKey:model.subType];
    NSString *className = [RZMessageCellTool messageCellClassMap][key];
    Class cellClass =  NSClassFromString(className);
    if([cellClass respondsToSelector:@selector(sizeForMessageModel:withCollectionViewWidth:referenceExtraHeight:)]) {
        CGFloat extraHeight = [RZMessageCellTool referenceExtraHeight:cellClass messageModel:model];
        CGSize size = [cellClass sizeForMessageModel:model
                             withCollectionViewWidth:collectionView.frame.size.width
                                referenceExtraHeight:extraHeight];

        //获取后，更新模型的cellSize reyzhang
        if (size.width != 0 && size.height != 0) {
            model.cellSize = size;
            return size;
        }
    }
    return CGSizeZero;
}




- (CGSize)collectionView:(UICollectionView *)collectionView
                             layout:(UICollectionViewLayout *)collectionViewLayout
    referenceSizeForHeaderInSection:(NSInteger)section {
    CGFloat width = self.conversationMessageCollectionView.frame.size.width;
    CGFloat height = 0;
    // 当加载本地历史消息小于 10 时，allMessagesAreLoaded 为 NO，此时高度设置为 0，否则会向下偏移 COLLECTION_VIEW_REFRESH_CONTROL_HEIGHT 的高度
    if(!self.dataSource.allMessagesAreLoaded) {
        if (self.conversationDataRepository.count < self.defaultRemoteHistoryMessageCount) {
            height = 0;
        } else {
            height = COLLECTION_VIEW_REFRESH_CONTROL_HEIGHT;
        }
    }
    return (CGSize){width, height};
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
}


#pragma mark - Hook钩子
- (RZMessageContent *)willSendMessage:(RZMessageContent *)message {
    NSLog(@"super %s", __FUNCTION__);
    return message;
}

- (RZMessage *)willAppendAndDisplayMessage:(RZMessage *)message {
    NSLog(@"super %s", __FUNCTION__);
    return message;
}

- (void)appendAndDisplayMessage:(RZMessage *)message{
//    [self.dataSource appendAndDisplayMessage:message];
}

- (void)didSendMessage:(NSInteger)status content:(RZMessageContent *)messageContent {
    NSLog(@"super %s, %@", __FUNCTION__, messageContent);
}

- (void)didCancelMessage:(RZMessageContent *)messageContent {
    NSLog(@"super %s, %@", __FUNCTION__, messageContent);
}

#pragma mark - 点击Cell事件
//点击cell
- (void)didTapMessageCell:(RZMessageInfo *)model {
    NSLog(@"%s", __FUNCTION__);
    if (nil == model) {
        return;
    }

    if (model.subType == MessageType_AUDIO) { //播放语音消息

        NSUInteger row = [self.conversationDataRepository indexOfObject:model];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        RZVoiceMessageCell *cell =
            (RZVoiceMessageCell *)[self.conversationMessageCollectionView cellForItemAtIndexPath:indexPath];
        if (cell) {
            [cell playVoice]; //播放音频
        }
    }else if (model.subType == MessageType_PICTURE) { //预览图片
        [self presentImagePreviewController:model onlyPreviewCurrentMessage:YES];
    }else if (model.subType == MessageType_VIDEO) { //预览视频
        [self presentVideoPreviewController:model];
    }

    
}


/**
 预览图片
 */
- (void)presentImagePreviewController:(RZMessageInfo *)model
            onlyPreviewCurrentMessage:(BOOL)onlyPreviewCurrentMessage {
    RZImageSlideViewController *_imagePreviewVC = [[RZImageSlideViewController alloc] init];
    _imagePreviewVC.messageModel = model;
    _imagePreviewVC.onlyPreviewCurrentMessage = onlyPreviewCurrentMessage;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:_imagePreviewVC];

    if (self.navigationController) {
        //导航和原有的配色保持一直
        UIImage *image = [self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsDefault];
        [nav.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    }
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:nav animated:YES completion:nil];
}


/**
 预览视频
 */
- (void)presentVideoPreviewController:(RZMessageInfo *)model {
    RZVideoPreviewViewController *vc = [[RZVideoPreviewViewController alloc] init];
    vc.videoUrl = [NSURL URLWithString:model.msg];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

//长按消息内容
- (void)didLongTouchMessageCell:(RZMessageInfo *)model inView:(UIView *)view {
    //长按消息需要停止播放语音消息
    /*[self.util stopVoiceMessageIfNeed:model];

    self.chatSessionInputBarControl.inputTextView.disableActionMenu = YES;
    self.currentSelectedModel = model;
    if (![self.chatSessionInputBarControl.inputTextView isFirstResponder]) {
        //聊天界面不为第一响应者时，长按消息，UIMenuController不能正常显示菜单
        // inputTextView 是第一响应者时，不需要再设置 self 为第一响应者，否则会导致键盘收起
        [self becomeFirstResponder];
    }
    CGRect rect = [self.view convertRect:view.frame fromView:view.superview];

    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setMenuItems:[self getLongTouchMessageCellMenuList:model]];
    if (@available(iOS 13.0, *)) {
        [menu showMenuFromView:self.view rect:rect];
    } else {
        [menu setTargetRect:rect inView:self.view];
        [menu setMenuVisible:YES animated:YES];
    }
     */
}

#pragma mark - Send Message 发送消息
- (void)sendMessage:(RZMessageContent *)messageContent {
    messageContent = [self willSendMessage:messageContent];
    if (messageContent == nil) {
        return;
    }

    [[RZIMClient sharedClient] sendMessageWithGroupId:self.targetId content:messageContent success:^{
        NSLog(@"聊天消息发送成功");
    } error:^(RZErrorCode nErrorCode, NSString * _Nullable errorMessage) {
        NSLog(@"发送消息失败：%@",errorMessage);
    }];
}


#pragma mark - UIScrollViewDelegate

/**
 滚动时，收起键盘
 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.isTouchScrolled = YES;
    if (self.chatSessionInputBarControl.currentBottomBarStatus != KBottomBarDefaultStatus &&
        self.chatSessionInputBarControl.currentBottomBarStatus != KBottomBarRecordStatus) {
        [self.chatSessionInputBarControl resetToDefaultStatus];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // isTouchScrolled 只有人为滑动页面才需要加载更新或者更旧的消息
    // 其他的时机如 reloadData 和弹出键盘等不需要加载消息
    if (scrollView.contentOffset.y <= 0 && !self.dataSource.isIndicatorLoading && !self.dataSource.allMessagesAreLoaded &&
        self.isTouchScrolled) {
        [self.collectionViewHeader startAnimating];
        [self.dataSource scrollToLoadMoreHistoryMessage];
    } else if (scrollView.contentOffset.y + scrollView.frame.size.height >= scrollView.contentSize.height &&
               !self.dataSource.isIndicatorLoading && self.isTouchScrolled) {
//        [self.dataSource scrollToLoadMoreNewerMessage];
    }
}

#pragma mark - RCChatSessionInputBarControlDelegate 输入工具栏回调
- (BOOL)isRemainMessageExisted {
    return self.locatedMessageSentTime != 0;
}


- (void)scrollToBottomAnimated:(BOOL)animated {
    if ([self.conversationMessageCollectionView numberOfSections] == 0) {
        return;
    }

    NSUInteger finalRow = MAX(0, [self.conversationMessageCollectionView numberOfItemsInSection:0] - 1);
    if (finalRow == 0) {
        return;
    }
    NSIndexPath *finalIndexPath = [NSIndexPath indexPathForItem:finalRow inSection:0];
    [self.conversationMessageCollectionView scrollToItemAtIndexPath:finalIndexPath
                                                   atScrollPosition:UICollectionViewScrollPositionBottom
                                                           animated:animated];
    //页面滚动到最新处，右下方气泡消失
    [self.dataSource.unreadNewMsgArr removeAllObjects];
//    [self updateUnreadMsgCountLabel];
}



/**
 键盘或emoji表情或插件面板弹出时，改变collectionView的大小
 */
- (void)chatInputBar:(RZChatSessionInputBarControl *)chatInputBar shouldChangeFrame:(CGRect)frame {
//    if ([self updateReferenceViewFrame]) { //消息引用
//        return;
//    }
    CGRect collectionViewRect = self.conversationMessageCollectionView.frame;
    collectionViewRect.size.height = CGRectGetMinY(frame) - collectionViewRect.origin.y;
    if (!chatInputBar.hidden) {
        [self.conversationMessageCollectionView setFrame:collectionViewRect];
    }
    
    if (self.locatedMessageSentTime == 0 || self.isConversationAppear) {
        //在viewwillapear和viewdidload之前，如果强制定位，则不滑动到底部
        if (self.dataSource.isLoadingHistoryMessage || [self isRemainMessageExisted]) {
//            [self loadRemainMessageAndScrollToBottom:YES];
        } else {
            [self scrollToBottomAnimated:NO];
        }
    }
}


/**
 键盘上的完成按钮被点击的事件
 */
- (void)inputTextViewDidTouchSendKey:(UITextView *)inputTextView {
//    if ([self sendReferenceMessage:inputTextView.text]) {
//        return;
//    }
    RZMessageContent *content = [[RZMessageContent alloc] init];
    content.msg = inputTextView.text;
    content.msgType = MessageType_TEXT;
    [self sendMessage:content];
}

- (void)inputTextView:(UITextView *)inputTextView
    shouldChangeTextInRange:(NSRange)range
            replacementText:(NSString *)text {
    //接收 10 条以上消息,进入到聊天页面点击键盘使弹起,再次点击右上角 x 条未读消息,键盘输入文本，页面没有滚动到底部
    if (self.dataSource.isLoadingHistoryMessage || [self isRemainMessageExisted]) {
//        [self loadRemainMessageAndScrollToBottom:YES];
    }
}


/**
 插件面板， 选择工具项的事件
 */
- (void)pluginBoardView:(RZPluginBoardView *)pluginBoardView clickedItemWithTag:(NSInteger)tag {
    switch (tag) {
        case PLUGIN_BOARD_ITEM_ALBUM_TAG: {
            [self openSystemAlbum];
        } break;
        case PLUGIN_BOARD_ITEM_CAMERA_TAG: {
            [self openSystemCamera];
        } break;
        case PLUGIN_BOARD_ITEM_LOCATION_TAG: {
            //        [self openLocationPicker];
        } break;
        default: {
            [self openDynamicFunction:tag];
        } break;
            
    }
}

- (void)presentViewController:(UIViewController *)viewController functionTag:(NSInteger)functionTag {
    switch (functionTag) {
        case PLUGIN_BOARD_ITEM_ALBUM_TAG:
        case PLUGIN_BOARD_ITEM_CAMERA_TAG:
        case PLUGIN_BOARD_ITEM_LOCATION_TAG:
        case PLUGIN_BOARD_ITEM_FILE_TAG: {
            viewController.modalPresentationStyle = UIModalPresentationFullScreen;
            [self.navigationController presentViewController:viewController animated:YES completion:nil];
        } break;
        default: { } break;
    }
}


/**
 表情键盘的，选取表情事件
 */
- (void)emojiView:(RZEmojiBoardView *)emojiView didTouchedEmoji:(NSString *)touchedEmoji {
    //TODO:可以发送正在输入的消息
}


/**
 表情键盘的 发送事件
 */
- (void)emojiView:(RZEmojiBoardView *)emojiView didTouchSendButton:(UIButton *)sendButton {
    RZMessageContent *content = [[RZMessageContent alloc] init];
    content.msg = self.chatSessionInputBarControl.inputTextView.text;
    content.msgType = MessageType_TEXT;
    [self sendMessage:content];
}


/*!
 开始录制语音消息
 */
- (void)recordDidBegin {
    NSLog(@"语音开始录制");
}

/*!
 取消录制语音消息
 */
- (void)recordDidCancel {
    NSLog(@"语音录制取消");
}

/*!
 结束录制语音消息
 */
- (void)recordDidEnd:(NSData *)recordData
          recordFile:(NSURL *)recordFile
            duration:(long)duration
               error:(nonnull NSError *)error {

    if (!recordData && !recordFile) {
        return;
    }
    
    //音频转格式
    //录音格式转换，从wav转为amr
//    NSString *amrFilePath = [[recordFile.path stringByDeletingPathExtension]
//                             stringByAppendingPathExtension:@"amr"];
//    BOOL convertResult = [RZKitUtility convertWAV:recordFile.path toAMR:amrFilePath];
    
    
    NSString *mp3FilePath = [[recordFile.path stringByDeletingPathExtension] stringByAppendingString:@".mp3"];
    BOOL convertResult = [RZKitUtility convertWAV:recordFile.path toMP3:mp3FilePath];
    if (convertResult) {
        // 删除录的wav
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm removeItemAtPath:recordFile.path error:nil];
    }else {
        return;
    }
    
    //先上传音频，再发送socket消息
    [RZApiManager uploadWithFiles:@[mp3FilePath] progress:^(int progress) {
        
    } success:^(NSDictionary * _Nonnull dic) {
        if ([dic isSuccess]) {
            NSString *path = dic[kResponseDataKey];
            
            RZMessageContent *content = [[RZMessageContent alloc] init];
            content.msg = path;
            content.msgType = MessageType_AUDIO;
            content.extraData = @{@"duration":@(duration)};
            [self sendMessage:content];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}


//图片选择回调
- (void)imageDataDidSelect:(NSArray *)selectedImages fullImageRequired:(BOOL)full {
    [self becomeFirstResponder];
    if (selectedImages.count == 0) {
        return;
    }
    
    //先上传图片，再发送socket消息
    [RZApiManager uploadWithFiles:selectedImages progress:^(int progress) {
        
    } success:^(NSDictionary * _Nonnull dic) {
        if ([dic isSuccess]) {
            NSString *path = dic[kResponseDataKey];
            
            NSArray *imageArray = [path componentsSeparatedByString:@","];
            if (imageArray.count == selectedImages.count) {
                for (int i=0; i<imageArray.count; i++) {
                    NSString *imageUrl = imageArray[i];
                    UIImage *image = selectedImages[i];
                    RZMessageContent *content = [[RZMessageContent alloc] init];
                    content.msg = imageUrl;
                    content.msgType = MessageType_PICTURE;
                    content.extraData = @{@"width":@(image.size.width),@"height":@(image.size.height)};
                    [self sendMessage:content];
                }
            }
        }
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"图片消息， 图片上传失败");
    }];
    
}


/**
 拍摄 回调
 */
- (void)sightDidFinishRecord:(NSString *)url thumbnail:(UIImage *)image duration:(NSUInteger)duration {
    if (url.length > 0) { //视频文件
        
        NSArray *files = @[image,url]; //先第一帧图片， 再视频
        [RZApiManager uploadWithFiles:files progress:^(int progress) {
            
        } success:^(NSDictionary * _Nonnull dic) {
            if ([dic isSuccess]) {
                NSString *result = dic[kResponseDataKey];
                NSArray *fileArray = [result componentsSeparatedByString:@","];
                
                //发送视频消息
                RZMessageContent *content = [[RZMessageContent alloc] init];
                content.msg = fileArray.lastObject;
                content.msgType = MessageType_VIDEO;
                content.extraData = @{@"width":@(image.size.width),@"height":@(image.size.height), @"imageUrl":fileArray.firstObject, @"duration":@(duration)};
                [self sendMessage:content];
            }
        } failure:^(NSError * _Nonnull error) {
            NSLog(@"视频消息， 视频上传失败");
        }];
        
        
    }else {
        NSArray *files = @[image];
        [RZApiManager uploadWithFiles:files progress:^(int progress) {
            
        }  success:^(NSDictionary * _Nonnull dic) {
            if ([dic isSuccess]) {
                NSString *result = dic[kResponseDataKey];
        
                //发送图片消息
                RZMessageContent *content = [[RZMessageContent alloc] init];
                content.msg = result;
                content.msgType = MessageType_PICTURE;
                content.extraData = @{@"width":@(image.size.width),@"height":@(image.size.height)};
                [self sendMessage:content];
            }
        } failure:^(NSError * _Nonnull error) {
            NSLog(@"图片消息， 图片上传失败");
        }];
    }
}

#pragma mark 输入工具栏各种扩展功能点击事件
//打开系统相册
- (void)openSystemAlbum {
    [self.chatSessionInputBarControl openSystemAlbum];
}
//打开相机
- (void)openSystemCamera {
    [self.chatSessionInputBarControl openSystemCamera];
}

//打开其他的 Extention 功能，如音视频功能
- (void)openDynamicFunction:(NSInteger)functionTag {
    
}

#pragma mark Lazy
- (UITapGestureRecognizer *)resetBottomTapGesture {
    if (!_resetBottomTapGesture) {
        _resetBottomTapGesture =
            [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap4ResetDefaultBottomBarStatus:)];
//        [_resetBottomTapGesture setDelegate:self];
        _resetBottomTapGesture.cancelsTouchesInView = NO;
        _resetBottomTapGesture.delaysTouchesEnded = NO;
    }
    return _resetBottomTapGesture;
}


- (UICollectionView *)conversationMessageCollectionView {
    if (!_conversationMessageCollectionView) {
        self.flowLayout = [[RZConversationViewLayout alloc] init];
        self.flowLayout.sectionInset = UIEdgeInsetsMake(20, 0, 0, 0);
        //frame
        CGRect _conversationViewFrame = [UIScreen mainScreen].bounds;
        CGFloat _conversationViewFrameY = 64+[UIManager sharedManager].safeAreaTop;

        _conversationViewFrame.size.height =
            [UIScreen mainScreen].bounds.size.height - self.chatSessionInputBarControl.frame.size.height - _conversationViewFrameY - [UIManager sharedManager].safeAreaBottom;
        
        
        _conversationMessageCollectionView =
            [[UICollectionView alloc] initWithFrame:_conversationViewFrame collectionViewLayout:self.flowLayout];
        
        self.flowLayout.collectionViewNewContentSize = _conversationMessageCollectionView.contentSize;
        
        
        [_conversationMessageCollectionView setBackgroundColor:[UIColor clearColor]];
        _conversationMessageCollectionView.showsHorizontalScrollIndicator = NO;
        _conversationMessageCollectionView.alwaysBounceVertical = YES;

        _conversationMessageCollectionView.dataSource = self;
        _conversationMessageCollectionView.delegate = self;
        
        if (@available(iOS 11.0, *)) {
            _conversationMessageCollectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
        }
    }
    return _conversationMessageCollectionView;
}


- (RZChatSessionInputBarControl *)chatSessionInputBarControl {
    if (!_chatSessionInputBarControl) {
        CGFloat _frameY = 64 + [UIManager sharedManager].safeAreaTop;
        _chatSessionInputBarControl = [[RZChatSessionInputBarControl alloc]
                                       initWithFrame:CGRectMake(0, self.view.bounds.size.height - ChatSessionInputBar_Height -
                                                                       [UIManager sharedManager].safeAreaBottom - _frameY,
                                                                self.view.bounds.size.width, ChatSessionInputBar_Height)
                                   withContainerView:self.view
                                    defaultInputType:self.defaultInputType];
        _chatSessionInputBarControl.delegate = self;
        [self.view addSubview:_chatSessionInputBarControl];
    }
    return _chatSessionInputBarControl;
}



@end
